package org.fog.json.io;

import org.dom4j.Document;
import org.dom4j.Element;
import org.fog.json.common.JsonFieldType;
import org.fog.json.common.JsonType;
import org.fog.json.map.*;

import java.util.List;
import java.util.TreeMap;

/**
 * User: 缪凯
 * Date: 12-2-8
 * Time: 下午2:58
 */
public class JsonMapParserImp implements JsonMapParser {
    private Document doc = null;

    private TreeMap<String, JsonMapBody> jsonMapBodies = null;

    private JsonMapPackage jsonMapPackage = null;

    public JsonMapParserImp(Document doc){
        if(doc != null){
            this.doc = doc;
            this.parser();
        }
    }

    private void parser(){
        //获得根节点
        Element root = this.doc.getRootElement();
        this.jsonMapPackage = new JsonMapPackageImp(root.attributeValue("Package"));
        this.jsonMapBodies = new TreeMap<String, JsonMapBody>();
        //获取当前配置中的所有json配置
        List<Element> jsons = root.elements("json");
        //循环构造json
        for (Element json : jsons){
            String id = json.attributeValue("id");
            String type = json.attributeValue("type");
            //获得当前json的所有属性Map
            List<Element> fields = json.element("body").elements("field");
            JsonMapField[] fieldBeans = this.makeFieldBeans(fields.size());
            //循环构造属性
            for(int i = 0 ; i < fieldBeans.length ; i++){
                fieldBeans[i].setName(fields.get(i).attributeValue("name"));
                fieldBeans[i].setPackage(fields.get(i).attributeValue("Package"));
                fieldBeans[i].setReflex(fields.get(i).attributeValue("ref"));
                fieldBeans[i].setOrder(i);
                fieldBeans[i].setType(Enum.valueOf(JsonFieldType.class , fields.get(i).attributeValue("type")));
            }
            //创建json实体
            this.jsonMapBodies.put(id, new JsonMapBodyImp
                    (id, Enum.valueOf(JsonType.class, type), this.jsonMapPackage, fieldBeans));
        }
        //将包指向实体
        this.jsonMapPackage.setBodies(this.jsonMapBodies);
    }


    private JsonMapField[] makeFieldBeans(int length){
        //构造容纳JsonMap属性的数组
        JsonMapField[] fieldBeans  = new JsonMapField[length];
        for(int i = 0 ; i < length ; i++)
            fieldBeans[i] = new JsonMapField();
        return fieldBeans;
    }

    public JsonMapPackage getPackage() {
        return this.jsonMapPackage;
    }

    public TreeMap<String, JsonMapBody> getBodies() {
        return this.jsonMapBodies;
    }
}
